package com.changgou.goods.controller;

import com.changgou.entity.PageResult;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.goods.pojo.Brand;
import com.changgou.goods.service.BrandService;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;
    //查询全部
    @GetMapping
    public Result<List<Brand>> findList(){
        List<Brand> brandList = brandService.findList();
        return new Result(true, StatusCode.OK,"查询成功",brandList) ;
    }
    //按照ID查询品牌
    @GetMapping("/{id}")
    public Result<Brand> findById(@PathVariable("id") Integer id){
        Brand byId = brandService.findById(id);
        return new Result(true,StatusCode.OK,"查询成功",byId);
    }

    //添加数据,使用postmapping添加
    @PostMapping("/add")
    //由于是post返回的数据,有可能是json数据,所以需要@RequestBody来解析数据封装进实体类中
    public Result add(@RequestBody Brand brand){
        brandService.add(brand);
        return new Result(true,StatusCode.OK,"添加成功");
    }
    //修改数据
    @PutMapping("/{id}")
    public Result update(@PathVariable("id") Integer id,@RequestBody Brand brand){
        brand.setId(id);
        brandService.update(brand);
        return new Result(true,StatusCode.OK,"修改成功");
    }

    //删除数据
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id){
        brandService.delete(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    //根据条件查询数据
    @GetMapping("/search")
    public Result<List<Brand>> search(@RequestParam Map searchMap){
        List<Brand> list = brandService.list(searchMap);
        return new Result<>(true,StatusCode.OK,"查询成功",list);
    }

    //分页查询
    @GetMapping("/findPage/{page}/{size}")
    public Result findPage(@PathVariable("page")int page,@PathVariable("size")int size){
        //直接调用接口
        Page<Brand> page1 = brandService.findPage(page, size);
        PageResult<Brand> pageResult = new PageResult<>(page1.getTotal(),page1.getResult());
        return new Result(true,StatusCode.OK,"查询成功",pageResult);
    }
    //分页查询+条件查询
    @GetMapping("/search/{page}/{size}")
    public Result findPage(@RequestParam Map searchMap,@PathVariable("page")int page,@PathVariable("size")int size){
        //int i = 1/0;
        Page pageInfo = brandService.findPage(searchMap, page, size);
        PageResult pageResult = new PageResult(pageInfo.getTotal(),pageInfo.getResult());
        return new Result(true,StatusCode.OK,"查询成功",pageResult);
    }
}
